/**
 * Created by lx on 2018/4/3.
 */
CommonUtils.regNamespace("com.im.moneyPlaneManage.moneyWrite");

$(function() {
    com.im.moneyPlaneManage.moneyWrite.invoke.init();
});

com.im.moneyPlaneManage.moneyWrite.invoke = function() {
    var client = new com.im.common.ajax();
    var tmpfiles;//文件上传下载

    /**
     * 页面初始化
     * @private
     */
    function _init() {
        //初始化时间、复选框、下拉框等事件和样式
        _initCommpentAction();
        _initFormValidate();
        //资金计划列表查询
        $("#vQueryMoneys").on("click", function () {
            _queryMoneys(1);
        }).trigger("click");
        //条件重置
        $("#vResetCond").on("click", _resetCond);
        //资金计划新增
        $("#vAddMoney").on("click", function() {
            _showEditMoney();
        });
        //修改资金计划
        $("#vEditMoney").on("click", _editMoney);
        //查询-建设单位to实施项目
        $("#searchOrgName").project2unit2itemCommpent({
            elmIdPlanTypeSel : "",
            elmIdUnitSel : "searchOrgName",//组织单位下拉元素
            elmIdItemSel : "vSubjectName",//实施项目下拉元素
            orgType : "10",//初始化单位时，单位类型
            callbackFunc: function (callBackType, ret) {//下拉框值改变时回调
                _queryMoneys(1);
            }
        });
      //新增编辑-建设单位to实施项目
        $("#orgUnit").project2unit2itemCommpent({
            elmIdPlanTypeSel : "",
            elmIdUnitSel : "orgUnit",//组织单位下拉元素
            elmIdItemSel : "impleProjName",//实施项目下拉元素
            orgType : "10",//初始化单位时，单位类型
            callbackFunc: function (callBackType, ret) {//下拉框值改变时回调
                //_callBackOrg(objvalue, objname);
                //callBackType : 1 所属规划值变更 2单位值变更  3项目名称变更
                //ret: orgId,orgName,impleProjId,impleProjName,planProjClass,planProjClassName
                if(callBackType == 3) {
                    var req = {};
                    req.impleProjId = ret.impleProjId;
                    req.declareType = 20;
                    var resp = client.callAsJson("fundPlanService/queryFundPlanListForGreen", req);
                    if (resp.success) {

                        var fund1 = _getFundDto(resp.result.fundDetailVo,'planProjMoney');
                        var fund2 = _getFundDto(resp.result.fundDetailVo,'implProjMoney');
                        var fund3 = _getFundDto(resp.result.fundDetailVo,'investPlanMoney');
                        var fund4 = _getFundDto(resp.result.fundDetailVo,'fundPlanMoney');
                        $("#buFund1").val(fund1.fundBu);
                        $("#shengFund1").val(fund1.fundSheng);
                        $("#gaoFund1").val(fund1.fundGao);
                        $("#qiFund1").val(fund1.fundQi);
                        $("#shiFund1").val(fund1.fundShi);
                        $("#otherFund1").val(fund1.fundOther);
                        $("#total1").val(fund1.total);

                        $("#buFund2").val(fund2.fundBu);
                        $("#shengFund2").val(fund2.fundSheng);
                        $("#gaoFund2").val(fund2.fundGao);
                        $("#qiFund2").val(fund2.fundQi);
                        $("#shiFund2").val(fund2.fundShi);
                        $("#otherFund2").val(fund2.fundOther);
                        $("#total2").val(fund2.total);

                        $("#buFund3").val(fund3.fundBu);
                        $("#shengFund3").val(fund3.fundSheng);
                        $("#gaoFund3").val(fund3.fundGao);
                        $("#qiFund3").val(fund3.fundQi);
                        $("#shiFund3").val(fund3.fundShi);
                        $("#otherFund3").val(fund3.fundOther);
                        $("#total3").val(fund3.total);

                        $("#buFund4").val(fund4.fundBu);
                        $("#shengFund4").val(fund4.fundSheng);
                        $("#gaoFund4").val(fund4.fundGao);
                        $("#qiFund4").val(fund4.fundQi);
                        $("#shiFund4").val(fund4.fundShi);
                        $("#otherFund4").val(fund4.fundOther);
                        $("#total4").val(fund4.total);


                        //本次投资计划里面的金额，默认剩余的额度
                        $("#vBbz").val(fund1.fundBu-fund4.fundBu);
                        $("#vScz").val(fund1.fundSheng-fund4.fundSheng);
                        $("#vGsslrz").val(fund1.fundGao-fund4.fundGao);
                        $("#vQyzc").val(fund1.fundQi-fund4.fundQi);
                        $("#vSzpt").val(fund1.fundShi-fund4.fundShi);
                        $("#vother").val(fund1.fundOther-fund4.fundOther);
                        $("#total5").val(fund1.total-fund4.total);
                        if(fund1.fundBu-fund4.fundBu < 0){
                            $("#vBbz").val(0);
                        }
                        if(fund1.fundSheng-fund4.fundSheng < 0){
                            $("#vScz").val(0);
                        }
                        if(fund1.fundGao-fund4.fundGao < 0){
                            $("#vGsslrz").val(0);
                        }
                        if(fund1.fundQi-fund4.fundQi < 0){
                            $("#vQyzc").val(0);
                        }
                        if(fund1.fundShi-fund4.fundShi < 0){
                            $("#vSzpt").val(0);
                        }
                        if(fund1.fundOther-fund4.fundOther < 0){
                            $("#vother").val(0);
                        }
                        if(fund1.total-fund4.total < 0){
                            $("#total5").val(0);
                        }
                    }
                }
            }
        });
        //初始化第一页
        _queryMoneys(1);
        //失去聚焦
        $("#vBbz").keyup(function () {
            _initTotal();
        });
        $("#vScz").keyup(function () {
            _initTotal();
        });
        $("#vGsslrz").keyup(function () {
            _initTotal();
        });
        $("#vQyzc").keyup(function () {
            _initTotal();
        });
        $("#vSzpt").keyup(function () {
            _initTotal();
        });
        $("#vother").keyup(function () {
            _initTotal();
        });
    }

    function _initTotal() {
        var b = $("#vBbz").val();
        var s = $("#vScz").val();
        var g = $("#vGsslrz").val();
        var q = $("#vQyzc").val();
        var sh = $("#vSzpt").val();
        var o= $("#vother").val();

        var tmp = 0;
        if(b != ''){
            tmp = tmp + parseFloat(b);
        }
        if(s != ''){
            tmp = tmp + parseFloat(s);
        }
        if(g != ''){
            tmp = tmp + parseFloat(g);
        }
        if(q != ''){
            tmp = tmp + parseFloat(q);
        }
        if(sh != ''){
            tmp = tmp + parseFloat(sh);
        }
        if(o != ''){
            tmp = tmp + parseFloat(o);
        }
        $("#total5").val(tmp.toFixed(2));
    }

    function _initCommpentAction() {
        //时间插件
    	$('#startDatepicker,#endDatepicker').datepicker({
        	startView: 'decade',  
            minView: 'decade',  
            format: 'yyyy',  
            maxViewMode: 2,  
            minViewMode:2,  
            autoclose: true 
        });

        //复选框
        $('input[type="checkbox"].minimal, input[type="radio"].minimal').iCheck({
            checkboxClass: 'icheckbox_minimal-blue',
            radioClass   : 'iradio_minimal-blue'
        });
        //下拉框
        $('.select2').select2();

        //项目查询组件
        $("body").append($($.parseHTML("<div class='modal fade bs-example-modal-lg' id='modal1' ></div>")));
        $("body").append($($.parseHTML("<div class='modal fade bs-example-modal-lg' id='modal2' ></div>")));
        $("#vQuerySubject").click(function() {
            $("#vQuerySubject").itemSearchCommpent({
                elmIdOut : "vSubjectName2",//组织树单击之后回填的文本框（input）
                elmIdModal : "modal1",//用户选择
                elmIdOrgModal : "modal2",//组织查询
                callbackFunc: function (projectId, projectName) {//组织树单击之后回调函数
                    $("#vSubjectName2").attr("vaSubjectId", projectId);
                    $('#addEditMoneyForm').data('bootstrapValidator').updateStatus('vSubjectName2', 'NOT_VALIDATED',null).validateField('vSubjectName2');
                }
            });
        });


        var req = {};
        req.declareType = 20;
        req.hasYearDt = 'Y';
        var result = client.callAsJson("investPlanService/queryDeclareSetIds", req);
        if (result.success) {
            var investApplyCode = $("#investApplyCode");
            investApplyCode.append("<option value='' selected='selected'>请选择</option>");
            $.each(result.result, function (i, item) {
                investApplyCode.append("<option value='" +  item.declareSetId  + "' year='" + item.yearDt + "' >" + item.declareCode + "</option>");
            });
            var searchDeclareSetName = $("#searchDeclareSetName");
           /* searchDeclareSetName.append("<option value='' selected='selected'>请选择</option>");*/
            $.each(result.result, function (i, item) {
            	searchDeclareSetName.append("<option value='" +  item.declareSetId  + "' year='" + item.yearDt + "' >" + item.declareCode + "</option>");
            });
        }
        
        $("#searchDeclareSetName").on("change",function(){
        	_queryMoneys(1);
        });
    }

    /**
     * 表单验证
     * @param $form
     * @returns {boolean}
     * @private
     */
    function _formValidate($form) {
        $form.data("bootstrapValidator").validate();
        return $form.data("bootstrapValidator").isValid();
    }

    /**
     * 表单验证初始化
     * @private
     */
    function _initFormValidate(flag) {
        $("#addEditMoneyForm").bootstrapValidator({
            live: 'enabled',
            excluded: [':hidden'],
            feedbackIcons: {valid: 'glyphicon glyphicon-ok', invalid: 'glyphicon glyphicon-remove', validating: 'glyphicon glyphicon-loadData'},
            fields: {
                vMoneyName2: {validators: {notEmpty: {message: "请填写资金计划名称"}}},
                investApplyCode: {validators: {notEmpty: {message: "请选择资金计划申报编码"}}},
                impleProjName: {validators: {notEmpty: {message: "请选择实施项目"}}},
                orgUnit: {validators: {notEmpty: {message: "请选择建设单位"}}},
                startDatepicker: {trigger:"change",validators: {notEmpty: {message: "请选择开工年"}}},
                endDatepicker: {trigger:"change",validators: {
                    notEmpty: {message: "请选择完工年"},
                    callback: {message: "完工日期不能小于开工日期", callback:function(value, validator,$field){
                        if($("#startDatepicker").val() == null || $("#startDatepicker").val() == "" ||  $("#endDatepicker").val() == null||  $("#endDatepicker").val() == ""){
                            return true;
                        }
                        return new Date($("#startDatepicker").val()) <= new Date($("#endDatepicker").val());
                    }}
                }},
                vBbz: {validators: {notEmpty: {message: "请填写部补助金额"}, numeric: {message: '部补助只能输入数字'}}},
                vScz: {validators: {notEmpty: {message: "请填写省财政金额"}, numeric: {message: '省财政只能输入数字'}}},
                vGsslrz: {validators: {notEmpty: {message: "请填写政府融资金额"}, numeric: {message: '政府融资只能输入数字'}}},
                vQyzc: {validators: {notEmpty: {message: "请填写部企业自筹金额"}, numeric: {message: '企业自筹只能输入数字'}}},
                vSzpt: {validators: {notEmpty: {message: "请填写市州配套金额"}, numeric: {message: '市州配套只能输入数字'}}},
                // vDescription: {validators: {notEmpty: {message: "请填写备注"}}}
            }
        });

        if(flag == undefined) {
            $('#addEditModal').on('hidden.bs.modal', function () {
                $('#addEditMoneyForm').data('bootstrapValidator').destroy();
                $('#addEditMoneyForm').data('bootstrapValidator', null);
                _initFormValidate("again");
            });
        }
    }

    /**
     * 条件重置
     * @private
     */
    function _resetCond() {
        $('#searchOrgName,#vSubjectName,#vMoneyName').val('');
        $('#searchOrgName').val("").trigger("change");
        $('#vSubjectName').val("").trigger("change");
        $('#searchDeclareSetName').val("").trigger("change");
        _queryMoneys(1);
    }

    /**
     * 资金计划列表查询
     * @param page
     * @param needTurn
     * @private
     */
    function _queryMoneys(index) {
        var vYear = $("#searchDeclareSetName option:selected").attr("year");

            com.im.moneyPlaneManage.moneyWrite.moneyColumns = [
                [{field:'vaSeq',title:"序号",rowspan:2,width:30,fitColumns:true,formatter: function(value,row,index){return index + 1;}},
                    //{field:'fundPlanCode',title:"资金计划编码",rowspan:2,width:150,fitColumns:true},
                    {field:'declareSetName',title:"资金计划申报批次",rowspan:2,width:100,fitColumns:true},
                    {field:'impleProjName',title:"实施项目名称",rowspan:2,width:100,fitColumns:true},
            	    {field:'developOrgName',title:"建设单位",width:100,fitColumns:true,rowspan:2},
                    {field:'JSNX',title:"建设年限",fitColumns:true,align:'center',colspan:2,},
                    {field:'preWorkSituation',title:"前期工作情况",fitColumns:true,align:'center',rowspan:2,},
                    {field:'GSTZ',colspan:7,title:'概算总投资（单位：万元）',align:'center'},
                    {field:'XDDJH',colspan:7,title:'累计至'+(vYear)+'年下达的计划（单位：万元）',align:'center'},
                    {field:'TZDZJ',colspan:7,title:'累计至'+(vYear)+'年完成的投资（单位：万元）',align:'center'},
                    {field:'DWDZJ',colspan:7,title:'累计至'+(vYear)+'年到位的资金（单位：万元）',align:'center'},
                    {field:'TZJH',colspan:7,title:''+(vYear)+'年填报资金计划（单位：万元）',align:'center'},
                    {field:'files',title:"填报附件",rowspan:2,width:100,fitColumns:true,formatter: function(value,row,index){
                        if(value.length > 0){
                            var fileNames = "";
                            $.each(value, function (i, item) {
                                fileNames += item.attachFullName + "  ";
                            });
                            return fileNames;
                        }else {
                            return "";
                        }
                    }},
                    {field:'description',title:"备注",rowspan:2,width:100,fitColumns:true,formatter: function(value,row,index){
                        if(value.length > 10){
                            return value.substr(0,10) + "...";
                        }else{
                            return value;
                        }
                    }},
                    {field:'statusName',title:"状态",rowspan:2,width:80,fitColumns:true},
                    {field:'vaOperation',title:"操作",rowspan:2,width:80,fitColumns:true,
           	         formatter: function(value,row,index){
         	            if(row.statusCd == '40' || row.statusCd == '60'){
                             //已初审、已批复不能修改
                             return '';
                         }else{
                    		return  "<a href='javascript:;' onclick='com.im.moneyPlaneManage.moneyWrite.invoke.showEditMoney("+ index +");' title='修改'><i class='fa fa-edit'></i></a> "+
                    			    "<a href='javascript:;' onclick='com.im.moneyPlaneManage.moneyWrite.invoke.deleteMoney("+ index +");' title='删除'><i class='fa fa-trash'></i></a>";
                         }
         	         }
                }],
                [{field:'investPlanStartDt',title:"开工年",fitColumns:true},
                    {field:'investPlanEndDt',title:"完工年",fitColumns:true},
                    {field:'total',title:"合计",fitColumns:true
                        ,formatter: function(value,row,index){
                            return _getColVal(row,'total','planProjMoney');
                        }
                    },
                    {field:'buFund',title:"部补助",fitColumns:true
                        ,formatter: function(value,row,index){
                            return _getColVal(row,'fundBu','planProjMoney');
                        }
                    },
                    {field:'shengFund',title:"省财政",fitColumns:true
                        ,formatter: function(value,row,index){
                            return _getColVal(row,'fundSheng','planProjMoney');
                        }
                    },
                    {field:'gaoFund',title:"政府融资",fitColumns:true
                        ,formatter: function(value,row,index){
                            return _getColVal(row,'fundGao','planProjMoney');
                        }
                    },
                    {field:'shiFund',title:"市州配套",fitColumns:true
                        ,formatter: function(value,row,index){
                            return _getColVal(row,'fundShi','planProjMoney');
                        }
                    },
                    {field:'qiFund',title:"企业自筹",fitColumns:true
                        ,formatter: function(value,row,index){
                            return _getColVal(row,'fundQi','planProjMoney');
                        }
                    },
                    {field:'otherFund',title:"其他",fitColumns:true
                        ,formatter: function(value,row,index){
                            return _getColVal(row,'fundOther','planProjMoney');
                        }
                    },
                    {field:'total1',title:"合计",fitColumns:true
                        ,formatter: function(value,row,index){
                            return _getColVal(row,'total','implProjMoney');
                        }
                    },
                    {field:'buFund1',title:"部补助",fitColumns:true
                        ,formatter: function(value,row,index){
                            return _getColVal(row,'fundBu','implProjMoney');
                        }
                    },
                    {field:'shengFund1',title:"省财政",fitColumns:true
                        ,formatter: function(value,row,index){
                            return _getColVal(row,'fundSheng','implProjMoney');
                        }
                    },
                    {field:'gaoFund1',title:"政府融资",fitColumns:true
                        ,formatter: function(value,row,index){
                            return _getColVal(row,'fundGao','implProjMoney');
                        }
                    },
                    {field:'shiFund1',title:"市州配套",fitColumns:true
                        ,formatter: function(value,row,index){
                            return _getColVal(row,'fundShi','implProjMoney');
                        }
                    },
                    {field:'qiFund1',title:"企业自筹",fitColumns:true
                        ,formatter: function(value,row,index){
                            return _getColVal(row,'fundQi','implProjMoney');
                        }
                    },
                    {field:'otherFund1',title:"其他",fitColumns:true
                        ,formatter: function(value,row,index){
                            return _getColVal(row,'fundOther','implProjMoney');
                        }
                    },
                    {field:'total2',title:"合计",fitColumns:true
                        ,formatter: function(value,row,index){
                            return _getColVal(row,'total','investPlanMoney');
                        }
                    },
                    {field:'buFund2',title:"部补助",fitColumns:true
                        ,formatter: function(value,row,index){
                            return _getColVal(row,'fundBu','investPlanMoney');
                        }
                    },
                    {field:'shengFund2',title:"省财政",fitColumns:true
                        ,formatter: function(value,row,index){
                            return _getColVal(row,'fundSheng','investPlanMoney');
                        }
                    },
                    {field:'gaoFund2',title:"政府融资",fitColumns:true
                        ,formatter: function(value,row,index){
                            return _getColVal(row,'fundGao','investPlanMoney');
                        }
                    },
                    {field:'shiFund2',title:"市州配套",fitColumns:true
                        ,formatter: function(value,row,index){
                            return _getColVal(row,'fundShi','investPlanMoney');
                        }
                    },
                    {field:'qiFund2',title:"企业自筹",fitColumns:true
                        ,formatter: function(value,row,index){
                            return _getColVal(row,'fundQi','investPlanMoney');
                        }
                    },
                    {field:'otherFund2',title:"其他",fitColumns:true
                        ,formatter: function(value,row,index){
                            return _getColVal(row,'fundOther','investPlanMoney');
                        }
                    },
                    {field:'total3',title:"合计",fitColumns:true
                        ,formatter: function(value,row,index){
                            return _getColVal(row,'total','fundPlanMoney');
                        }
                    },
                    {field:'buFund3',title:"部补助",fitColumns:true
                        ,formatter: function(value,row,index){
                            return _getColVal(row,'fundBu','fundPlanMoney');
                        }
                    },
                    {field:'shengFund3',title:"省财政",fitColumns:true
                        ,formatter: function(value,row,index){
                            return _getColVal(row,'fundSheng','fundPlanMoney');
                        }
                    },
                    {field:'gaoFund3',title:"政府融资",fitColumns:true
                        ,formatter: function(value,row,index){
                            return _getColVal(row,'fundGao','fundPlanMoney');
                        }
                    },
                    {field:'shiFund3',title:"市州配套",fitColumns:true
                        ,formatter: function(value,row,index){
                            return _getColVal(row,'fundShi','fundPlanMoney');
                        }
                    },
                    {field:'qiFund3',title:"企业自筹",fitColumns:true
                        ,formatter: function(value,row,index){
                            return _getColVal(row,'fundQi','fundPlanMoney');
                        }
                    },
                    {field:'otherFund3',title:"其他",fitColumns:true
                        ,formatter: function(value,row,index){
                            return _getColVal(row,'fundOther','fundPlanMoney');
                        }
                    },
                    {field:'total0',title:"合计",fitColumns:true
                        ,formatter: function(value,row,index){
                            return _getColVal(row,'total','fundWriteMoney');
                        }
                    },
                    {field:'buFund0',title:"部补助",fitColumns:true
                        ,formatter: function(value,row,index){
                            return _getColVal(row,'fundBu','fundWriteMoney');
                        }
                    },
                    {field:'shengFund0',title:"省财政",fitColumns:true
                        ,formatter: function(value,row,index){
                            return _getColVal(row,'fundSheng','fundWriteMoney');
                        }
                    },
                    {field:'gaoFund0',title:"政府融资",fitColumns:true
                        ,formatter: function(value,row,index){
                            return _getColVal(row,'fundGao','fundWriteMoney');
                        }
                    },
                    {field:'shiFund0',title:"市州配套",fitColumns:true
                        ,formatter: function(value,row,index){
                            return _getColVal(row,'fundShi','fundWriteMoney');
                        }
                    },
                    {field:'qiFund0',title:"企业自筹",fitColumns:true
                        ,formatter: function(value,row,index){
                            return _getColVal(row,'fundQi','fundWriteMoney');
                        }
                    },
                    {field:'otherFund0',title:"其他",fitColumns:true
                        ,formatter: function(value,row,index){
                            return _getColVal(row,'fundOther','fundWriteMoney');
                        }
                    }
                ]
            ];
        var req = {};
        req.pageInfo = {};
        req.pageInfo.pageNumber = index;
        req.pageInfo.pageSize = 20;
        req.developOrg = $("#searchOrgName option:selected").attr("value");
        req.impleProjId = $("#vSubjectName").val();
        req.declareSetId =  $("#searchDeclareSetName option:selected").attr("value");
        var resp = client.callAsJson("fundPlanService/queryFundPlanList", req);
        //var resp = client.callAsJson("fundPlanService/queryShFundPlanListNew", req);
        if (!resp.success) {
            toastr.error(resp.resultMsg);
            return;
        }

        $("#vMoneyTable").empty();
        $("#vMoneyTable").datagrid({
            nowrap:false,
            fitColumns:true,
        	pagination:true,
        	columns:com.im.moneyPlaneManage.moneyWrite.moneyColumns,
        	data:resp.result
        });
        var p = $('#vMoneyTable').datagrid('getPager');
        $(p).pagination({
            pageSize: 20,
            pageList: [10,20,30],
            beforePageText: '第',
            afterPageText: '页    共 {pages}  页',
            displayMsg: '当前显示 {from} - {to} 条记录 共 {total}  条记录',
            onSelectPage:function(pageNumber, pageSize){
                _queryMoneys(pageNumber);
            }
        });
    }

    function _showEditMoney(index) {
        if(index == undefined) {
            $('#addEditModal .modal-title').html('资金计划新增')
            //文件
            var file = new com.im.common.file();
            tmpfiles = file.activate(1);

            var result = client.callAsJson("commonService/getSeq", {'tableName':'T_FUND_PLAN'});
            $("#vMoneyId").val("");
            $("#vMoneyCode").val(result.result.seq);
            $("#vMoneyName2").val("");
            $("#vSubjectName2").val("");
            $("#vSubjectName2").attr("vaSubjectId", "");
            $("#startDatepicker").val("");
            $("#endDatepicker").val("");

            $("#vBbz").val("");
            $("#vScz").val("");
            $("#vGsslrz").val("");
            $("#vQyzc").val("");
            $("#vSzpt").val("");
            $("#total5").val("");


            $("#buFund").val("");
            $("#shengFund").val("");
            $("#gaoFund").val("");
            $("#qiFund").val("");
            $("#shiFund").val("");
            $("#otherFund").val("");
            $("#description").val("");

            $("#buFund1").val("");
            $("#shengFund1").val("");
            $("#gaoFund1").val("");
            $("#qiFund1").val("");
            $("#shiFund1").val("");
            $("#otherFund1").val("");
            $("#total").val("");

            $("#buFund2").val("");
            $("#shengFund2").val("");
            $("#gaoFund2").val("");
            $("#qiFund2").val("");
            $("#shiFund2").val("");
            $("#otherFund2").val("");
            $("#total2").val("");

            $("#buFund3").val("");
            $("#shengFund3").val("");
            $("#gaoFund3").val("");
            $("#qiFund3").val("");
            $("#shiFund3").val("");
            $("#otherFund3").val("");
            $("#total3").val("");

            $("#buFund4").val("");
            $("#shengFund4").val("");
            $("#gaoFund4").val("");
            $("#qiFund4").val("");
            $("#shiFund4").val("");
            $("#otherFund4").val("");
            $("#total4").val("");

            $("#vDescription").val("");
            $('#investApplyCode').val($('#investApplyCode option:eq(1)').attr('value')).trigger("change").attr('disabled',false);
            $('#orgUnit').val($('#orgUnit option:eq(1)').attr('value')).trigger("change").attr('disabled',false);
            $('#impleProjName').val($('#impleProjName option:eq(1)').attr('value')).trigger("change").attr('disabled',false);

        } else {
            $('#addEditModal .modal-title').html('资金计划修改');
            var row = $('#vMoneyTable').datagrid('getData').rows[index];
            $("#investApplyCode").val(row.declareSetId).trigger("change").attr('disabled',true);
            $("#orgUnit").val(row.developOrg).trigger("change").attr('disabled',true);
            $("#impleProjName").val(row.impleProjId).trigger("change").attr('disabled',true);
            $("#startDatepicker").val(row.investPlanStartDt);
            $("#endDatepicker").val(row.investPlanEndDt);

            $("#vMoneyId").val(row.fundPlanId);

            $("#vSubjectName2").val(row.investPlanStartDt);
            $("#vSubjectName2").attr("vaSubjectId", row.investPlanEndDt);

            $("#vDescription").val(com.im.common.util.descapeTextArea(row.description));

            //文件
            var file = new com.im.common.file();
            var fileList = row.files;
            $.each(fileList,function (index,item){
            	fileList[index].fileSuffix = item.attachFullName;
            	fileList[index].uploadName = item.attachFullName;
            	fileList[index].filePath = item.attachPath;
            });
            tmpfiles = file.activate(1, fileList);
            var fund1 = _getFundDto(row.fundDetailVo,'planProjMoney');
            var fund2 = _getFundDto(row.fundDetailVo,'implProjMoney');
            var fund3 = _getFundDto(row.fundDetailVo,'investPlanMoney');
            var fund4 = _getFundDto(row.fundDetailVo,'fundPlanMoney');
            var fund = _getFundDto(row.fundDetailVo,'fundWriteMoney');

            $("#buFund1").val(fund1.fundBu);
            $("#shengFund1").val(fund1.fundSheng);
            $("#gaoFund1").val(fund1.fundGao);
            $("#qiFund1").val(fund1.fundQi);
            $("#shiFund1").val(fund1.fundShi);
            $("#otherFund1").val(fund1.fundOther);
            $("#total1").val(fund1.total);

            $("#buFund2").val(fund2.fundBu);
            $("#shengFund2").val(fund2.fundSheng);
            $("#gaoFund2").val(fund2.fundGao);
            $("#qiFund2").val(fund2.fundQi);
            $("#shiFund2").val(fund2.fundShi);
            $("#otherFund2").val(fund2.fundOther);
            $("#total2").val(fund2.total);

            $("#buFund3").val(fund3.fundBu);
            $("#shengFund3").val(fund3.fundSheng);
            $("#gaoFund3").val(fund3.fundGao);
            $("#qiFund3").val(fund3.fundQi);
            $("#shiFund3").val(fund3.fundShi);
            $("#otherFund3").val(fund3.fundOther);
            $("#total3").val(fund3.total);

            $("#buFund4").val(fund4.fundBu);
            $("#shengFund4").val(fund4.fundSheng);
            $("#gaoFund4").val(fund4.fundGao);
            $("#qiFund4").val(fund4.fundQi);
            $("#shiFund4").val(fund4.fundShi);
            $("#otherFund4").val(fund4.fundOther);
            $("#total4").val(fund4.total);
            //本次投资计划里面的金额，默认剩余的额度
            $("#vBbz").val(fund.fundBu);
            $("#vScz").val(fund.fundSheng);
            $("#vGsslrz").val(fund.fundGao);
            $("#vQyzc").val(fund.fundQi);
            $("#vSzpt").val(fund.fundShi);
            $("#vother").val(fund.fundOther);
            $("#total5").val(fund.total);

            // var req = {};
            // req.impleProjId = row.impleProjId;
            // req.declareType = 20;
            // var resp = client.callAsJson("investPlanService/queryProjectAndTotalFoundSource", req);
            // if (resp.success) {
            //     var fund1 = resp.result[0];
            //     var fund2 = resp.result[1];
            //     $("#buFund1").val(fund1.FundBu);
            //     $("#shengFund1").val(fund1.FundSheng);
            //     $("#gaoFund1").val(fund1.FundGao);
            //     $("#qiFund1").val(fund1.FundQi);
            //     $("#shiFund1").val(fund1.FundShi);
            //     $("#total").val(fund1.total);
            //     $("#buFund2").val(fund2.FundBu);
            //     $("#shengFund2").val(fund2.FundSheng);
            //     $("#gaoFund2").val(fund2.FundGao);
            //     $("#qiFund2").val(fund2.FundQi);
            //     $("#shiFund2").val(fund2.FundShi);
            //     $("#total2").val(fund2.total);
            // }
        }
        $("#addEditModal").modal("show");
    }
    
    function _editMoney() {
        if(!_formValidate($("#addEditMoneyForm"))) {
            return;
        }

        var req = {};
        req.fundPlanId = $("#vMoneyId").val();
        req.declareSetId = $("#investApplyCode").val();
        req.impleProjId= $("#impleProjName").val();
        req.fundSourceBu = $("#vBbz").val();
        req.fundSourceSheng = $("#vScz").val();
        req.fundSourceGao = $("#vGsslrz").val();
        req.fundSourceQi = $("#vQyzc").val();
        req.fundSourceShi = $("#vSzpt").val();
        req.fundSourceOther= $("#vother").val();
        req.description = com.im.common.util.escapeTextArea($("#vDescription").val());

        if($("#vMoneyId").val() == '') {
        	req.yearDt = $("#investApplyCode option:selected").attr('year');
            if(tmpfiles == undefined || tmpfiles.newly.length == 0){
                var result = client.callAsJson("fundPlanService/addFundPlan", req);
                if(result.resultCode=='0'){
                    toastr.success("资金计划增加成功");
                    _queryMoneys(1);
                }else {
                    toastr.error(result.result.message);
                }
            }else{
                client.callAsFile(tmpfiles.newly, function(fileRes) {
                    if(fileRes.success){
                        req.addFiles = fileRes.result;
                        var result = client.callAsJson("fundPlanService/addFundPlan", req);
                        if(result.resultCode=='0'){
                            toastr.success("资金计划新增成功");
                            _queryMoneys(1);
                        }else {
                            toastr.error("服务器忙！请稍后再试！"+result.resultMsg);
                        }
                    }else{
                        toastr.error('文件服务器忙！请稍后再试！');
                    }
                });
            }

        } else {
            if(tmpfiles.newly == undefined || tmpfiles.newly.length == 0){
                req.delFiles = tmpfiles.del;
                var result = client.callAsJson("fundPlanService/updateFundPlan", req);
                if(result.resultCode=='0'){
                    toastr.success("资金计划修改成功");
                    _queryMoneys(1);
                }else {
                    toastr.error("服务器忙！请稍后再试！"+result.resultMsg);
                }
            }else{
                client.callAsFile(tmpfiles.newly, function(fileRes) {
                    if(fileRes.success){
                        req.addFiles = fileRes.result;
                        req.delFiles = tmpfiles.del;
                        var result = client.callAsJson("fundPlanService/updateFundPlan", req);
                        if(result.resultCode=='0'){
                            toastr.success("资金计划修改成功");
                            _queryMoneys(1);
                        }else {
                            toastr.error("服务器忙！请稍后再试！"+result.resultMsg);
                        }
                    }else{
                        toastr.error('文件服务器忙！请稍后再试！');
                    }
                });
            }
        }
        _queryMoneys(1);
        $("#addEditModal").modal("hide");
    }
    
    function _deleteMoney(index) {
        com.im.common.confirm("确认是否删除资金计划", null, function () {
            var row = $('#vMoneyTable').datagrid('getData').rows[index];

            var req = {};
            req.fundPlanId = row.fundPlanId;
            req.statusCd = '70';
            var resp = client.callAsJson("fundPlanService/deleteFundPlan", req);
            if (!resp.success) {
                toastr.error(resp.resultMsg);
                return;
            }
            toastr.success("删除资金计划成功");
            _queryMoneys(1);
        })
    }

    function _dateFormat(date) {
        var date = new Date(date);
        return date.getFullYear();
    }

    //数据类型
    //sourceValue,源数据
    //colName,列名
    //type,资金计划类型
    function _getColVal(sourceValue,colName,type){

        var val;
        $.each(sourceValue.fundDetailVo,function (i,obj) {
            if(obj.type  == type){
                val = obj[colName];
                return false;
            }
        });

        if(val == undefined || val == ''){
            val = '0';
        }
        return val;

    };

    //sourceValue,源数据
    //colName,列名
    //type,资金计划类型
    function _getFundDto(sourceValue,type){

        var val;
        $.each(sourceValue,function (i,obj) {
            if(obj.type  == type){
                val = obj;
                return false;
            }
        });

        if(val == undefined || val == ''){
            val = {};
            val.type =  type;
            val.total = '0';
            val.fundBu = '0';
            val.fundSheng = '0';
            val.fundGao = '0';
            val.fundShi = '0';
            val.fundQi = '0';
            val.fundOther = '0';
            //val.statusCd;
            //val.remark;
            //val.fileName;
        }
        return val;

    };

    return {
        init : _init,
        showEditMoney : _showEditMoney,
        deleteMoney : _deleteMoney
    }
}();